package com.xianyun.book.command;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.Assert;
import com.alibaba.cola.extension.ExtensionExecutor;
import com.xianyun.book.common.core.event.DomainEventPublisher;
import com.xianyun.book.domain.gateway.SystemUserGateway;
import com.xianyun.book.domain.user.SystemUser;
import com.xianyun.book.dto.UserRegisterCmd;
import com.xianyun.book.dto.domainevent.UserRegisterEvent;
import com.xianyun.book.extensionpoint.AccountInitExtPt;
import com.xianyun.book.extensionpoint.RegisterValidatorExtPtExtPt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;


/**
 * @author macos-zyj
 */
@Slf4j
@Component
public class UserRegisterCmdExe {
    @Resource
    private SystemUserGateway userGateway;

    @Resource
    private ExtensionExecutor extensionExecutor;

    @Resource
    private DomainEventPublisher domainEventPublisher;


    public Response execute(UserRegisterCmd registerCmd){

        //validation
        extensionExecutor.executeVoid(RegisterValidatorExtPtExtPt.class, registerCmd.getBizScenario(), extension -> extension.validator(registerCmd));

        //Convert CO to Entity
        SystemUser userEntity = extensionExecutor.execute(AccountInitExtPt.class, registerCmd.getBizScenario(), extension -> extension.initAccount(registerCmd));
        Assert.notNull(userEntity,"账号初始化不能为空!");
        userGateway.registerUser(userEntity);

        domainEventPublisher.publish(new UserRegisterEvent());

        log.info("End processing command:" + registerCmd);

        return  Response.buildSuccess();
    }
}
